package com.zfzs.post.modules.policy.service.impl;

import com.zfzs.post.modules.policy.domain.PolicyType;
import com.zfzs.post.modules.policy.domain.PolicyTypeInfo;
import com.zfzs.post.modules.policy.repository.PolicyTypeRepository;
import com.zfzs.post.modules.policy.service.PolicyTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 政策类型设置
 *
 * @author: ck
 * @create: 2019/8/20/15:16
 **/
@Service
public class PolicyTypeServiceImpl implements PolicyTypeService {

    @Autowired
    private PolicyTypeRepository policyTypeRepository;

    @Override
    public PolicyType findOne(PolicyType policyType) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                 .withMatcher("agentId", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("postId", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<PolicyType> ex = Example.of(policyType, matcher);
        Optional<PolicyType> p = policyTypeRepository.findOne(ex);
        if (!p.isPresent()) {
            return null;
        }
        return p.get();
    }

    @Override
    public PolicyType findById(String id) {
        Optional<PolicyType> p = policyTypeRepository.findById(id);
        if (!p.isPresent()) {
            return null;
        }
        return p.get();
    }

    @Override
    public PolicyType save(PolicyType policyType) {
        return policyTypeRepository.save(policyType);
    }

    @Override
    public List<PolicyType> queryAll() {
        return policyTypeRepository.findAll();
    }

    @Override
    public PolicyType findbyPolicyTypeName(String policyTypeName) {
        return policyTypeRepository.findByPolicyTypeName(policyTypeName);
    }

    @Override
    public PolicyTypeInfo queryPolicyTypeInfo(String id,String typeId) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("id", ExampleMatcher.GenericPropertyMatchers.contains());
        PolicyType PolicyType = new PolicyType();
        PolicyType.setId(id);
        Example<PolicyType> ex = Example.of(PolicyType, matcher);
        Optional<PolicyType> p = policyTypeRepository.findOne(ex);
        if (!p.isPresent()) {
            return null;
        }
        PolicyType policy = p.get();
        List<PolicyTypeInfo> list = policy.getList();
        for (int i = 0; i < list.size(); i++) {
            String poTypeId = list.get(i).getTypeId();
            if(poTypeId.equals(typeId)){
                return list.get(i);
            }
        }
        return null;
    }
}
